package com.ruoyi.course.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.assertj.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.course.domain.LabCourse;
import com.ruoyi.course.domain.LabCourseDate;
import com.ruoyi.course.domain.LabCourseTimetable;
import com.ruoyi.course.mapper.LabCourseTimetableMapper;
import com.ruoyi.course.service.ILabCourseTimetableService;

/**
 * 课程时间Service业务层处理
 * 
 * @author jun.wang
 * @date 2022-04-05
 */
@Service
public class LabCourseTimetableServiceImpl implements ILabCourseTimetableService {
	@Autowired
	private LabCourseTimetableMapper labCourseTimetableMapper;

	/**
	 * 查询课程时间
	 * 
	 * @param timetableId
	 *            课程时间ID
	 * @return 课程时间
	 */
	@Override
	public LabCourseTimetable selectLabCourseTimetableById(Long timetableId) {
		return labCourseTimetableMapper.selectLabCourseTimetableById(timetableId);
	}

	/**
	 * 查询课程时间列表
	 * 
	 * @param labCourseTimetable
	 *            课程时间
	 * @return 课程时间
	 */
	@Override
	public List<LabCourseTimetable> selectLabCourseTimetableList(LabCourseTimetable labCourseTimetable) {
		return labCourseTimetableMapper.selectLabCourseTimetableList(labCourseTimetable);
	}

	/**
	 * 新增课程时间
	 * 
	 * @param labCourseTimetable
	 *            课程时间
	 * @return 结果
	 */
	@Override
	@Transactional
	public int insertLabCourseTimetable(LabCourseTimetable labCourseTimetable) {
		if(labCourseTimetable.getLastDate().before(new Date())){
			throw new RuntimeException("该学期已经结束，不能加添加.");
		}
		if(labCourseTimetable.getCourseStartDate().after(labCourseTimetable.getCourseEndDate())){
			throw new RuntimeException("该学期起始日期晚于结束日期，不能加添加.");
		}
		if(labCourseTimetable.getCourseEndDate().after(labCourseTimetable.getLastDate())){
			throw new RuntimeException("该学期结束日期晚于最后日期，不能加添加.");
		}
		LabCourseTimetable oldTimetable = this.getDefaultTimetable(labCourseTimetable.getCourseStartDate());
		if(oldTimetable==null){
			oldTimetable = this.getDefaultTimetable(labCourseTimetable.getLastDate());
		}
		if(oldTimetable!=null){
			if (oldTimetable.getCourseEndDate().after(labCourseTimetable.getCourseStartDate())){
				throw new RuntimeException("该学期的日期和录入的其他学期有日期重合，不能加添加.");
			}
		}
		try {
			labCourseTimetable.setRemark(LabCourseTimetable.mapper.writerWithDefaultPrettyPrinter().writeValueAsString((labCourseTimetable.getCourseOffDayList())));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw new RuntimeException("节日序列化失败:"+e.getMessage());
		}
		labCourseTimetable.setCreateBy(SecurityUtils.getUsername());
		labCourseTimetable.setCreateTime(DateUtils.getNowDate());
		labCourseTimetable.setUpdateBy(SecurityUtils.getUsername());
		labCourseTimetable.setUpdateTime(DateUtils.getNowDate());
		return labCourseTimetableMapper.insertLabCourseTimetable(labCourseTimetable);
	}
	
	public LabCourseTimetable getDefaultTimetable(Date lastDate){
		LabCourseTimetable query = new LabCourseTimetable();
		query.setLastDate(lastDate);
		List<LabCourseTimetable> list = this.selectLabCourseTimetableList(query);
		if(list.size()>1){
			throw new RuntimeException("错误：学期日历数据的存在日期区间重合，请检查日历数据并修正.");
		}
		if(list.size()>0){
			return list.get(0);
		}
		return null;
	}

	/**
	 * 修改课程时间
	 * 
	 * @param labCourseTimetable
	 *            课程时间
	 * @return 结果
	 */
	@Override
	public int updateLabCourseTimetable(LabCourseTimetable labCourseTimetable) {
		if(labCourseTimetable.getLastDate().before(new Date())){
			throw new RuntimeException("该学期已经结束，不能修改.");
		}
		if(labCourseTimetable.getCourseStartDate().after(labCourseTimetable.getCourseEndDate())){
			throw new RuntimeException("该学期起始日期晚于结束日期，不能修改.");
		}
		if(labCourseTimetable.getCourseEndDate().after(labCourseTimetable.getLastDate())){
			throw new RuntimeException("该学期结束日期晚于最后日期，不能修改.");
		}
		LabCourseTimetable oldTimetable = this.getDefaultTimetable(labCourseTimetable.getCourseStartDate());
		if(oldTimetable==null || oldTimetable.getTimetableId().longValue()!=labCourseTimetable.getTimetableId().longValue()){
			oldTimetable = this.getDefaultTimetable(labCourseTimetable.getLastDate());
		}
		if(oldTimetable!=null && oldTimetable.getTimetableId().longValue()!=labCourseTimetable.getTimetableId().longValue()){
			if (oldTimetable.getCourseEndDate().after(labCourseTimetable.getCourseStartDate())){
				throw new RuntimeException("该学期的日期和其他学期有日期重合，不能修改.");
			}
		}
		try {
			labCourseTimetable.setRemark(LabCourseTimetable.mapper.writerWithDefaultPrettyPrinter().writeValueAsString((labCourseTimetable.getCourseOffDayList())));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw new RuntimeException("节日序列化失败:"+e.getMessage());
		}
		labCourseTimetable.setUpdateBy(SecurityUtils.getUsername());
		labCourseTimetable.setUpdateTime(DateUtils.getNowDate());
		return labCourseTimetableMapper.updateLabCourseTimetable(labCourseTimetable);
	}

	/**
	 * 批量删除课程时间
	 * 
	 * @param timetableIds
	 *            需要删除的课程时间ID
	 * @return 结果
	 */
	@Override
	public int deleteLabCourseTimetableByIds(Long[] timetableIds) {
		return labCourseTimetableMapper.deleteLabCourseTimetableByIds(timetableIds);
	}

	/**
	 * 删除课程时间信息
	 * 
	 * @param timetableId
	 *            课程时间ID
	 * @return 结果
	 */
	@Override
	public int deleteLabCourseTimetableById(Long timetableId) {
		return labCourseTimetableMapper.deleteLabCourseTimetableById(timetableId);
	}
	

	public List<LabCourseDate> getDates(LabCourse labCourse) {
		Long timetableId = labCourse.getTimetableId();
		LabCourseTimetable labCourseTimetable = labCourseTimetableMapper.selectLabCourseTimetableById(timetableId);

		Date courseStartDate = DateUtils.addDays(labCourseTimetable.getCourseStartDate(), 7*(labCourse.getWeekOpenNums()-1));
		labCourse.setCourseDate(courseStartDate);
		//包含最后一周但不包含最后一天
		List<LabCourseDate> labCourseDateList = new ArrayList<LabCourseDate>();
		if(labCourse.getDay1()!=null){
			String sectionValue = labCourse.getDay1();
			LabCourseDate courseDate = getWeekDay(labCourse, 1, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay2()!=null){
			String sectionValue = labCourse.getDay2();
			LabCourseDate courseDate = getWeekDay(labCourse, 2, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay3()!=null){
			String sectionValue = labCourse.getDay3();
			LabCourseDate courseDate = getWeekDay(labCourse, 3, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay4()!=null){
			String sectionValue = labCourse.getDay4();
			LabCourseDate courseDate = getWeekDay(labCourse, 4, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay5()!=null){
			String sectionValue = labCourse.getDay5();
			LabCourseDate courseDate = getWeekDay(labCourse, 5, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay6()!=null){
			String sectionValue = labCourse.getDay6();
			LabCourseDate courseDate = getWeekDay(labCourse, 6, sectionValue);
			labCourseDateList.add(courseDate);
		}
		if(labCourse.getDay7()!=null){
			String sectionValue = labCourse.getDay7();
			LabCourseDate courseDate = getWeekDay(labCourse, 7, sectionValue);
			labCourseDateList.add(courseDate);
		}
		return labCourseDateList;
	}

	private LabCourseDate getWeekDay(LabCourse labCourse, int day, String sectionValue) {
		LabCourseDate courseDate = new LabCourseDate();
		courseDate.setTimetableId(labCourse.getTimetableId());
		courseDate.setWeekNum(labCourse.getWeekOpenNums());
		courseDate.setCourseDate(DateUtils.addDays(labCourse.getCourseDate(), day-1));
		if(StringUtils.isNotEmpty(sectionValue)){
			String[] sectionArr = sectionValue.split("-");
			try{
				if(sectionArr.length<2){
					//throw new RuntimeException();
					courseDate.setSectionStart(Integer.valueOf(sectionArr[0]));
					courseDate.setSectionEnd(Integer.valueOf(sectionArr[0]));
				}else{
					courseDate.setSectionStart(Integer.valueOf(sectionArr[0]));
					courseDate.setSectionEnd(Integer.valueOf(sectionArr[1]));
				}
			}catch(Exception e){
				throw new RuntimeException("节次输入不正确，格式应为:数字 或 数字-数字 实际为:"+labCourse.getDay2());
			}
		}
		return courseDate;
	}
	
	/*private static List<Date> getCourseDates(Date startDate, Date endDate, int weekDay) {
		List<Date> dates = new ArrayList<>();
		Calendar instance = Calendar.getInstance();
		instance.setTime(startDate);
		while (instance.getTime().compareTo(endDate) <= 0) {
			int dayOfWeek = instance.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek == weekDay) {
				dates.add(instance.getTime());
			}
			instance.add(Calendar.DAY_OF_YEAR, 1);
		}
		return dates;
	}*/
}
